package com.betterjr.modules.application.service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.betterjr.common.service.BaseService;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.Collections3;
import com.betterjr.common.utils.QueryTermBuilder;
import com.betterjr.common.utils.UserUtils;
import com.betterjr.modules.application.IApplicationUndercarriage;
import com.betterjr.modules.application.dao.ApplicationOperatorMapper;
import com.betterjr.modules.application.data.ApplicationCustRoleConstantCollections;
import com.betterjr.modules.application.data.ApplicationGroupConstantCollections;
import com.betterjr.modules.application.data.ApplicationOperatorConstantCollections;
import com.betterjr.modules.application.data.ApplicationOperorgConstantCollections;
import com.betterjr.modules.application.entity.Application;
import com.betterjr.modules.application.entity.ApplicationOperator;
import com.google.common.collect.Lists;

/**
 * 
 * @ClassName: ApplicationOperatorService 
 * @Description: 个人应用定制表 
 * @author xuyp
 * @date 2017年11月30日 下午1:41:30 
 *
 */
@Service
public class ApplicationOperatorService extends BaseService<ApplicationOperatorMapper, ApplicationOperator>
        implements IApplicationUndercarriage {

    @Autowired
    private ApplicationService applicationService;

    /**
     * 
     * @Title: queryApplicationOperatorList 
     * @Description: 查询应用操作员表
     * @param anApplicationGroupId  组id
     * @param anApplicationTypeId   类型id
     * @param anBusinStatus         状态  状态 1未生效 2已生效 9已失效
     * @param anOperatorId     操作员id
     * @return 
     * @throws 
     * @author xuyp
     * @date 2017年11月29日 上午9:46:06
     */
    public List<ApplicationOperator> queryApplicationOperatorList(String anBusinStatus, Long anOperatorId,
            Map<String, Object> anBuilder) {

        Map<String, Object> build = createParamMap(anBuilder);
        /**
         * .put("operOrg", UserUtils.getOperatorInfo().getOperOrg())
                .put("operatorId", UserUtils.getOperatorInfo().getId())
         */

        if (null != anOperatorId) {
            build.put("operatorId", anOperatorId);
        }

        if (StringUtils.isBlank(anBusinStatus)) {
            build.put("businStatus", ApplicationCustRoleConstantCollections.APPLICATIONCUSTROLE_BUSINSTATUS_EFFECTIVE);
        } else {
            if (anBusinStatus.contains(ApplicationGroupConstantCollections.SYSTEM_VALUE_FILE_SEPARATOR)) {
                build.put("businStatus",
                        anBusinStatus.split(ApplicationGroupConstantCollections.SYSTEM_VALUE_FILE_SEPARATOR));
            } else {
                build.put("businStatus", anBusinStatus);
            }
        }

        return this.selectByProperty(build, "proprityLevel asc ,id desc");

    }

    /**
     * 
     * @Title: queryApplicationsCurrentUser 
     * @Description: 查询应用
     * @param anApplicationGroupId  组id
     * @param anApplicationTypeId   类型id
     * @param anBusinStatus         状态  状态 1未生效 2已生效 9已失效
     * @param anOperatorId     操作员id
     * @throws 
     * @author xuyp
     * @date 2017年11月29日 上午9:48:19
     */
    public List<Application> queryApplicationsCurrentUser(String anBusinStatus, Long anOperatorId,
            Map<String, Object> anBuilder) {

        if (anOperatorId == null) {
            anOperatorId = UserUtils.getOperatorInfo().getId();
        }
        List<ApplicationOperator> operatorList = this.queryApplicationOperatorList(anBusinStatus, anOperatorId,
                anBuilder);
        if (Collections3.isEmpty(operatorList)) {
            return Lists.newArrayList();
        }

        List<Application> applicationList = new ArrayList<>(operatorList.size());
        for (ApplicationOperator operator : operatorList) {
            applicationList.add(applicationService.selectByPrimaryKey(operator.getApplicationId()));
        }

        return applicationList;

    }

    /**
     * 
     * @Title: saveAddOrUpdateApplicationOperator 
     * @Description: 新增或者修改个性化设置 
     * @param filterFalg
     * @param proprityLevel
     * @param applicationId
     * @param operatorId
     * @param proprity
     * @return 
     * @throws 
     * @author xuyp
     * @date 2017年11月30日 上午9:30:04
     */
    @SuppressWarnings("unchecked")
    public ApplicationOperator saveAddOrUpdateApplicationOperator(Map<String, Object> anMap) {

        BTAssert.notNull(anMap, "数据为空,操作失败");
        BTAssert.notNull(anMap.get("applicationId"), "数据为空,操作失败");
        // anMap = createParamMap(anMap);
        Map<String, Object> map = QueryTermBuilder.newInstance().put("operatorId", UserUtils.getOperatorInfo().getId())
                .put("applicationId", anMap.get("applicationId"))
                .put("businStatus", ApplicationCustRoleConstantCollections.APPLICATIONCUSTROLE_BUSINSTATUS_EFFECTIVE)
                .build();
        List<ApplicationOperator> applicationOperatorList = this.selectByProperty(map, "id Desc");
        if (Collections3.isEmpty(applicationOperatorList)) {
            // 新增

            return saveAddApplicationOperator(anMap);

        } else {
            // 修改
            if (applicationOperatorList.size() > 1) {
                // 处理脏数据
                for (int i = 1; i < applicationOperatorList.size(); i++) {
                    ApplicationOperator operator = applicationOperatorList.get(i);
                    operator.setBusinStatus(
                            ApplicationCustRoleConstantCollections.APPLICATIONCUSTROLE_BUSINSTATUS_DELETED);
                    this.updateByPrimaryKeySelective(operator);
                }

            }

            return saveUpdateApplicationOperator(Collections3.getFirst(applicationOperatorList), anMap);

        }

    }

    /**
     * 
     * @Title: saveUpdateApplicationOperator 
     * @Description: 更新个人应用定制表
     * @param anApplicationOperator
     * @param anMap
     * @return 
     * @throws 
     * @author xuyp
     * @date 2017年11月30日 下午1:40:08
     */
    private ApplicationOperator saveUpdateApplicationOperator(ApplicationOperator anApplicationOperator,
            Map<String, Object> anMap) {

        if (anMap.containsKey(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_FILTERFALG)) {

            anApplicationOperator.setFilterFalg(
                    anMap.get(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_FILTERFALG).toString());
        }
        if (anMap.containsKey(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_PROPRITY)) {

            anApplicationOperator.setProprity(
                    anMap.get(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_PROPRITY).toString());

        }

        if (anMap.containsKey(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_PROPRITYLEVEL)) {
            anApplicationOperator.setProprityLevel(Integer.parseInt(anMap
                    .get(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_PROPRITYLEVEL).toString()));
        }

        this.updateByPrimaryKeySelective(anApplicationOperator);

        return anApplicationOperator;
    }

    /**
     * 
     * @Title: saveAddApplicationOperator 
     * @Description: 根据map新增一条应用个性记录 
     * @param anMap
     * @return 根据map新增一条应用个性记录 
     * @throws 
     * @author xuyp
     * @date 2017年11月30日 上午11:18:09
     */
    private ApplicationOperator saveAddApplicationOperator(Map<String, Object> anMap) {

        ApplicationOperator applicationOperator = new ApplicationOperator().saveAddValue(
                Long.parseLong(anMap.get("applicationId").toString()), UserUtils.getOperatorInfo().getId());
        applicationOperator.setOperatorName(UserUtils.getOperatorInfo().getName());
        if (anMap.containsKey(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_FILTERFALG)) {

            applicationOperator.setFilterFalg(
                    anMap.get(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_FILTERFALG).toString());
        }
        if (anMap.containsKey(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_PROPRITY)) {

            applicationOperator.setProprity(
                    anMap.get(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_PROPRITY).toString());
            if (anMap.containsKey(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_PROPRITYLEVEL)) {
                applicationOperator.setProprityLevel(Integer.parseInt(
                        anMap.get(ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_FIELD_PROPRITYLEVEL)
                                .toString()));
            } else {
                applicationOperator.setProprityLevel(
                        ApplicationOperatorConstantCollections.APPLICATIONOPERATOR_PROPRITYLEVEL_DEFAULT);
            }
        }
        this.insertSelective(applicationOperator);

        return applicationOperator;
    }

    /**
     * 
     * @Title: createParamMap 
     * @Description: 创建查询条件
     * @param anBuilder
     * @return 
     * @throws 
     * @author xuyp
     * @date 2017年11月29日 上午10:10:41
     */

    @SuppressWarnings("unchecked")
    private Map<String, Object> createParamMap(Map<String, Object> anBuilder) {

        Field[] fields = ApplicationOperator.class.getDeclaredFields();
        if (Collections3.isEmpty(anBuilder)) {
            anBuilder = QueryTermBuilder.newInstance().build();
        }
        String[] fieldNameArray = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            fieldNameArray[i] = fields[i].getName();
        }
        anBuilder = Collections3.filterMapEmptyObject(anBuilder);
        anBuilder = Collections3.filterMap(anBuilder, fieldNameArray);

        return anBuilder;
    }

    /**
     * 应用表中此条应用下架
     * <p>Overriding Method of saveUndercarriageApplication</p>  
     * <p>Description: </p> 
     * @param anApplicationId 
     * @see com.betterjr.modules.application.IApplicationUndercarriage#saveUndercarriageApplication(java.lang.Long) 
     * @author xuyp
     * @date 2017年11月29日 上午10:16:37
     */
    @SuppressWarnings("unchecked")
    @Override
    public void saveUndercarriageApplication(Long anApplicationId) {

        if (null != anApplicationId) {
            List<ApplicationOperator> applicationOperatorList = queryApplicationOperatorList(
                    ApplicationOperorgConstantCollections.APPLICATIONOPERORG_BUSINSTATUS_CANUSED, null,
                    QueryTermBuilder.newInstance().put("applicationId", anApplicationId).build());
            for (ApplicationOperator applicationOperator : applicationOperatorList) {
                applicationOperator
                        .setBusinStatus(ApplicationOperorgConstantCollections.APPLICATIONOPERORG_BUSINSTATUS_DELETED);
                this.updateByPrimaryKeySelective(applicationOperator);
            }
        }

    }

}
